import { observe } from '../core/observer.js';

class Store {
  constructor(options) {
    this.state = options.state;
    this.mutations = options.mutations;
    this.actions = options.actions;
    this.modules = options.modules || {};

    this.installModule([], this.state, this.modules);
    observe(this.state);
  }

  installModule(path, state, module) {
    if (module.state) {
      if (path.length === 0) {
        Object.assign(state, module.state);
      } else {
        const parentState = path.slice(0, -1).reduce((state, key) => state[key], this.state);
        parentState[path[path.length - 1]] = module.state;
      }
    }

    const namespace = path.length ? path.join('/') + '/' : '';

    if (module.mutations) {
      Object.keys(module.mutations).forEach(key => {
        this.mutations[namespace + key] = module.mutations[key];
      });
    }

    if (module.actions) {
      Object.keys(module.actions).forEach(key => {
        this.actions[namespace + key] = module.actions[key];
      });
    }

    if (module.modules) {
      Object.keys(module.modules).forEach(key => {
        this.installModule([...path, key], state, module.modules[key]);
      });
    }
  }

  commit(type, payload) {
    if (this.mutations[type]) {
      this.mutations[type](this.state, payload);
    }
  }

  dispatch(type, payload) {
    if (this.actions[type]) {
      this.actions[type](this, payload);
    }
  }

  registerModule(path, module) {
    // 实现动态模块注册
  }

  mapState(namespace, map) {
    // 实现状态映射辅助函数
  }

  mapActions(namespace, map) {
    // 实现动作映射辅助函数
  }
}

export { Store };